﻿using ProductSystem.Model;
using Fundway.Common.Caching;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProductSystem.BLL.Common
{
    public class AuthenticationService
    {
        private static object locker = new object();
        private static AuthenticationService instance = new AuthenticationService();

        public static AuthenticationService Instance()
        {
            if (null == instance)
            {
                lock (locker)
                {
                    if (null == instance)
                    {
                        instance = new AuthenticationService();
                    }
                }
            }

            return instance;
        }

        public bool CheckUserFunction(int userId, string actionName)
        {
            bool isSuccess = false;

            System_Menu tempObj = FindObjByAction(actionName, userId);

            if (tempObj != null && tempObj.ID != 0)
                isSuccess = true;

            return isSuccess;
        }


        /// <summary>
        /// 判断用户有没有权限
        /// </summary>
        /// <param name="db">数据库</param>
        /// <param name="actionName">actionName</param>
        /// <param name="userId">用户ID</param>
        /// <returns>真/假</returns>
        private System_Menu FindObjByAction(string actionName, int userId)
        {
            string cacheKeyCode = "UserFunction-" + userId;
            //检查用户权限信息有没有放到缓存
            if (CacheRepository.Get(cacheKeyCode, true) == null)
                System_User_InfoBll.GetUserFuntion(userId);

            List<System_Menu> list = CacheRepository.Get(cacheKeyCode, true) as List<System_Menu>;
            System_Menu temp = new System_Menu();
            if (actionName.IndexOf('|') == -1)
            {
                temp = list.Find(delegate(System_Menu userFunction) { return actionName == userFunction.Menu_Controller + "-" + userFunction.Menu_Action; });
            }
            else
            {
                string[] actionNames = actionName.Split('|');
                foreach (string an in actionNames)
                {
                    temp = list.Find(delegate(System_Menu userFunction) { return an == userFunction.Menu_Controller + "-" + userFunction.Menu_Action; });
                    if (null != temp && temp.ID != 0)
                    {
                        break;
                    }
                }
            }
            return temp;
        }
    }
}
